<!--
*@Author: QWP
*@Description: 车辆基本信息编辑
*@Date: 2024-07-08 17:04:38
-->
<template>
  <u-dialog
    v-bind="$attrs"
    :confirmLoading="formLoading"
    destroyOnClose
    @submit="submit"
    @close="dialogClose">
    <a-layout class="f-h-100">
      <a-layout-content
        class="s-bg-white"
        style="overflow: auto">
        <a-space direction="vertical">
          <u-busi-card
            title="基本信息"
            :bordered="false">
            <u-form
              :elements="formEls"
              :model="form"
              :gutter="16"
              :loading="formLoading"
              @formChange="getUser"
              ref="formRef"></u-form>
          </u-busi-card>
          <u-busi-card title="车辆图片">
            <u-upload-img
              v-model:value="carImgs"
              :fileParams="{ biztype: '2', bucket: 'INC', maxCount: 1 }"
              accept=".jpg, .png, .jpeg, .gif" />
          </u-busi-card>
          <!-- <u-busi-card title="保险信息">
            <u-form :elements="insureFormEls"
              :model="insureForm"
              :gutter="16"
              :disabled="true"
              :loading="formLoading">
            </u-form>
          </u-busi-card> -->
          <u-busi-card
            title="承保记录"
            v-if="insureRecords.length != 0">
            <u-table
              :columns="insureRecordCols"
              :data="insureRecords"
              :rowSelection="null"
              :pagination="false"
              :scroll="{ y: 300 }"></u-table>
          </u-busi-card>
        </a-space>
      </a-layout-content>
    </a-layout>
  </u-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h, useAttrs, watch } from "vue";
import { useLoginStore, useBaseStore } from "@/store";
import { storeToRefs } from "pinia";
import { useRoute, useRouter } from "vue-router";
import { _IFormEl, _IExtra } from "@/src/components/common/form/interface";
import { FormInstance, FormItemProps } from "ant-design-vue";
import { HomeOutlined, FileTextOutlined, UploadOutlined } from "@ant-design/icons-vue";
import { TreeProps } from "ant-design-vue/es/vc-tree";
import { ColumnProps } from "ant-design-vue/es/table";
import { _IColumnProps } from "@/components/common/tableEdit/interface.ts";
import { fileCols } from "@/common/model/fileCols";
import { cloneDeep } from "lodash";
import { regions, depts, users, isSel } from "@/common/model/base";
import { alertC, messageC, numberC, isValue } from "@/util/common";
import { useSetViewPath } from "@/hooks/useFile";
import { insureFormEls, insureRecordCols } from "./data.ts";
import * as carApi from "@/service/administration/carBase";
import * as userApi from "@/service/system/user";
import * as unitService from "@/service/system/unit/index";
import * as deptApi from "@/service/system/dept";

interface Props {
  keyid?: string;
}
const props = defineProps<Props>();
const route = useRoute();
const attrs = useAttrs();
const { userInfo } = storeToRefs(useLoginStore());
const { unitData, deptData, IS_REIMBURSE, VEHICLE_MODEL, VEHICLE_TYPE, ISPROXY, VEHICLESTATUS } = storeToRefs(useBaseStore());

const emits = defineEmits(["success"]);

// 基础枚举
const baseData = reactive({
  deptData: deptData.value,
  userData: [],
  isreimburse: IS_REIMBURSE.value,
  carType: VEHICLE_MODEL.value,
  carOilType: VEHICLE_TYPE.value,
  isproxy: ISPROXY.value,
  carStatus: VEHICLESTATUS.value,
});

// 车辆图片
const carImgs = ref([]);

// 表单相关信息
const formRef = ref<FormInstance>();
const form = ref({});
const formLoading = ref<boolean>(false);
const formItemProps: FormItemProps & _IExtra = {
  labelWidth: "120px",
  colon: false,
};
const formEls: Array<_IFormEl> = reactive([
  {
    label: "所属单位",
    key: "unitName",
    col: { span: 8 },
    element: "input",
    formItemProps: { ...formItemProps, required: true },
    componentProps: { options: unitData.value, disabled: true },
  },
  {
    label: "所属部门",
    key: "ssdeptid",
    col: { span: 8 },
    element: "select",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      disabled: true,
      options: computed(() => baseData.deptData),
      fieldNames: { label: "name", value: "keyid" },
    },
  },
  {
    label: "车辆管理员",
    key: "vehicleadmin",
    col: { span: 8 },
    element: "select",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      options: computed(() => baseData.userData),
      fieldNames: { label: "username", value: "keyid" },
    },
  },
  { label: "品牌型号", key: "brandmodel", col: { span: 8 }, element: "input", formItemProps: { ...formItemProps, required: true } },
  {
    label: "车牌号",
    key: "platenumber",
    col: { span: 8 },
    element: "input",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      maxlength: 8,
      onChange: (value) => {
        form.value.platenumber = value.target.value.toLocaleUpperCase();
      },
    },
  },
  {
    label: "车型",
    key: "vehiclemodel",
    col: { span: 8 },
    element: "select",
    formItemProps: { ...formItemProps, required: true },
    componentProps: { options: baseData.carType },
  },
  { label: "车辆识别码", key: "vehiclecode", col: { span: 8 }, element: "input", formItemProps: { ...formItemProps, required: true } },
  { label: "发动机号", key: "enginenumber", col: { span: 8 }, element: "input", formItemProps: { ...formItemProps, required: true } },
  {
    label: "车辆类型",
    key: "vehicletype",
    col: { span: 8 },
    element: "select",
    formItemProps: { ...formItemProps, required: true },
    componentProps: { options: baseData.carOilType },
  },
  {
    label: "购置金额",
    key: "purchaseamount",
    col: { span: 8 },
    element: "money",
    formItemProps: { ...formItemProps, required: true },
    componentProps: { addonAfter: "元" },
  },
  {
    label: "耗油指标",
    key: "fuelconsumpindex",
    col: { span: 8 },
    element: "number",
    formItemProps: { ...formItemProps, required: false },
    componentProps: { addonAfter: "升/公里", precision: 2, controls: false },
  },
  {
    label: "排气量",
    key: "exhaustvolume",
    col: { span: 8 },
    element: "number",
    formItemProps: { ...formItemProps, required: computed(() => !isValue(form.value["turbocharging"])) },
    componentProps: {
      addonAfter: "自然吸气:L",
      precision: 1,
      controls: false,
      disabled: computed(() => isValue(form.value["turbocharging"])),
      onChange: () => formRef.value.form.validateFields(["turbocharging"]),
    },
  },
  {
    label: "排气量",
    key: "turbocharging",
    col: { span: 8 },
    element: "number",
    formItemProps: { ...formItemProps, required: computed(() => !isValue(form.value["exhaustvolume"])) },
    componentProps: {
      addonAfter: "涡轮增压:T",
      precision: 1,
      controls: false,
      disabled: computed(() => isValue(form.value["exhaustvolume"])),
      onChange: (val) => {
        formRef.value.form.validateFields(["exhaustvolume"])
      },
    },
  },
  {
    label: "当前截止公里数",
    key: "curmeliage",
    col: { span: 8 },
    element: "number",
    formItemProps: { ...formItemProps, required: true },
    componentProps: { addonAfter: "公里", precision: 0 },
  },
  {
    label: "是否代管",
    key: "isproxy",
    col: { span: 8 },
    element: "select",
    formItemProps: { ...formItemProps, required: true },
    componentProps: { options: baseData.isproxy },
  },
  {
    label: "车辆状况",
    key: "vehiclestatus",
    col: { span: 8 },
    element: "select",
    formItemProps: { ...formItemProps, required: true },
    componentProps: { options: baseData.carStatus },
  },
  { label: "备注", key: "remark", col: { span: 24 }, element: "textarea", formItemProps: { ...formItemProps } },
]);

// 保险相关信息
const insureForm = ref<object>({});
const insureRecords = ref<any[]>([]);

// 确认提交
const submit = async () => {
  try {
    await formRef.value.form.validate();
  } catch (error) {
    alertC("请将必填项填写完毕!", "warning");
    return;
  }

  const url = form.value.keyid ? "update" : "add";
  let copyform = cloneDeep(form.value);
  formLoading.vlaue = true;
  copyform.appendixSaveVOList = carImgs.value;
  try {
    const res = await carApi[url](copyform);
    if (res.code == 0) {
      messageC(res.msg, "success");
      emits("success");
    } else {
      alertC(res.msg, "warning");
    }
    dialogClose();
  } catch (error) {}
  formLoading.vlaue = false;
};

// 初始化默认保存传递的数据
const initBaseInfo = () => {
  form.value = {
    fkuserid: userInfo.value["userId"],
    fkusername: userInfo.value["name"],
    fkdeptid: userInfo.value["deptId"],
    redeptname: userInfo.value["deptName"],
    ssdeptid: userInfo.value["deptId"],
    ssdeptname: userInfo.value["deptName"],
    fkunitsid: userInfo.value["unitId"],
    unitName: userInfo.value["unitName"],
  };
};

// c初始化车辆信息表单
const initFormEls = () => {
  let elIndex = formEls.findIndex((i) => i.key == "ssdeptid");
  if (elIndex != -1) {
    let extra = userInfo.value["extra"] || {};
    let roles = extra["roles"] || {};
    let carRole = roles["6"] || [];
    formEls.splice(elIndex, 1, { ...formEls[elIndex], disabled: !carRole.some((i) => i.keyid == "1802538658906628097") });
  }
};

// 回显
const getHxData = async () => {
  formLoading.vlaue = true;
  // 表单信息
  try {
    const res = await carApi.query(props.keyid);

    if (res.code == 0) {
      form.value = res.data.vtVehicle || {};
      const imgs = form.value["appendix"] || [];
      imgs.forEach((item) => (item.url = item.filepath));
      carImgs.value = imgs;
    }

    // 保险信息
    insureRecords.value = res.data.vtInsurance || [];

    // 获取单位信息
    const unitInfo = await unitService.validTree("");

    if (unitInfo.code == 0) {
      form.value.unitName = (unitInfo.data || [{}])[0]["name"];
    }
    getUser({ key: "ssdeptid", value: form.value["ssdeptid"] });
    formLoading.vlaue = false;
  } catch (error) {
    formLoading.vlaue = false;
  }
};

// 获取枚举
const getysly = async () => {
  // 获取部门
  let unitId = userInfo.value["unitId"];
  if (unitId) {
    try {
      formLoading.value = true;
      const deptInfo = await deptApi.validTree(unitId);
      if (deptInfo.code == 0) {
        baseData.deptData = deptInfo.data || [];
      }
      formLoading.value = false;
    } catch (error) {
      formLoading.value = false;
    }
  }
  getUser({ key: "ssdeptid", value: form.value["ssdeptid"] });
};

// 点击下拉框获取人员
const getUser = async ({ key, value }) => {
  if (key == "ssdeptid") {
    const userData = await userApi.userPage({
      model: {
        fkunitsid: userInfo.value["unitId"],
        fkdeptid: value,
      },
      current: 1,
      size: 50000,
    });
    if (userData.code == 0) {
      baseData.userData = userData.data.records;
    }
    let deptName = baseData.deptData.find((i) => i.keyid == value);
    if (deptName) {
      form.value.ssdeptname = deptName.name;
    }
  } else if (key == "vehicleadmin") {
    let deptName = baseData.userData.find((i) => i.keyid == value);
    if (deptName) {
      form.value.vehicleadminname = deptName.username;
    }
  }
};

// 回显时获取人员
const getCarManagers = () => {
  announancement.getUserList({ deptId: form.value.ssdeptid }).then((res) => {
    if (res.data.code == 0) {
      baseData.userData = res.data.data || [];
    }
  });
};

// 弹窗关闭
const dialogClose = () => {
  formRef.value.form.resetFields();
  form.value = {};
  carImgs.value = [];
  insureRecords.value = [];
};

watch(
  () => attrs.open,
  async (nval, oval) => {
    if (nval == true) {
      initFormEls();
      if (props.keyid != "") {
        form.keyid = props.keyid;
        getHxData();
      } else {
        initBaseInfo();
      }
    }
  }
);
</script>

<style lang="scss"></style>
